package com.mf.storage;

import com.mf.storage.property.StorageProperties;
import com.mf.storage.service.ObjectStorageService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Constructor;
import java.util.Objects;

/**
 * 短信自动配置
 * User: zhaoming
 * Date: 2018-04-16
 * To change this template use File | Settings | File Templates.
 */
@Configuration
@ConditionalOnClass(ObjectStorageService.class)
@EnableConfigurationProperties({StorageProperties.class})
public class StorageAutoConfiguration {

    private static final Log logger = LogFactory.getLog(StorageAutoConfiguration.class);
    private final String COS_SERVICE_CLASS = "com.mf.storage.service.impl.CosObjectStorageServiceImpl";
    private final String OSS_SERVICE_CLASS = "com.mf.storage.service.impl.OssObjectStorageServiceImpl";
    private StorageProperties storageProperties;

    @Autowired
    public StorageAutoConfiguration(StorageProperties storageProperties) {
        this.storageProperties = storageProperties;
    }

    @Bean
    public ObjectStorageService objectStorageService() {
        ObjectStorageService objectStorageService;
        if(StringUtils.isBlank(storageProperties.getType())){
            throw new RuntimeException("存储服务自动配置：Type为必填项");
        }
        if(StringUtils.isBlank(storageProperties.getRegion())){
            throw new RuntimeException("存储服务自动配置：Region为必填项");
        }
        if(StringUtils.isBlank(storageProperties.getAccessKey())){
            throw new RuntimeException("存储服务自动配置：AccessKey为必填项");
        }
        if(StringUtils.isBlank(storageProperties.getSecretKey())){
            throw new RuntimeException("存储服务自动配置：SecretKey为必填项");
        }
        try {
            Class clazz;
            if(Objects.equals(storageProperties.getType(), "COS")){
                clazz = Class.forName(COS_SERVICE_CLASS);
            }else if(Objects.equals(storageProperties.getType(), "OSS")){
                clazz = Class.forName(OSS_SERVICE_CLASS);
            }else{
                clazz = Class.forName(COS_SERVICE_CLASS);
            }
            Constructor constructor = clazz.getConstructor(StorageProperties.class);
            objectStorageService = (ObjectStorageService) constructor.newInstance(storageProperties);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RuntimeException(e.getMessage(), e);
        }
        return objectStorageService;
    }
}
